package com.example.ssm1.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.ssm1.model.User;
import com.example.ssm1.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/list")
    public String getUserList(Model model){
        List<User> userList = userService.getUserList();
        model.addAttribute("userList",userList);
        return "user/userList";
    }

    @GetMapping("/detail")
    public String getUserDetail(Integer id,Model model){
        User user=userService.getUserDetail(id);
        model.addAttribute("user",user);
        return "user/userDetail";
    }

    @PostMapping("/upload")
    public String upload(Integer id, MultipartFile file){
        System.out.println(id);
        File file1=new File("E:\\idea2021\\ideaWorkSpace\\spring_demo\\ssm01\\src\\main\\resources\\upload"+File.separator+file.getOriginalFilename());
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:list";
    }

    @PostMapping("/upload2")
    @ResponseBody
    public JSONObject uploadAjax(MultipartFile file){
        File file1=new File("E:\\idea2021\\ideaWorkSpace\\spring_demo\\ssm01\\src\\main\\resources\\upload"+File.separator+file.getOriginalFilename());
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("fileUrl","/upload/"+file.getOriginalFilename());
        jsonObject.put("code",200);
        jsonObject.put("msg","上传成功");
        return jsonObject;
    }

}
